package project.service.impl;

import project.dao.BookDAO;
import project.dao.impl.BookDAOImpl;
import project.pojo.Book;
import project.pojo.Page;
import project.service.BookService;

import java.sql.SQLException;
import java.util.List;

/**
 * @author d11yu
 */
public class BookServiceImpl implements BookService {
    private BookDAO bookDAO = new BookDAOImpl();

    @Override
    public void addBook(Book book) {
        bookDAO.addBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
        bookDAO.deleteBookById(id);
    }

    @Override
    public void updateBookById(Book book) {
        bookDAO.updateBookById(book);
    }

    @Override
    public Book queryBookById(Integer id) throws SQLException {
        return bookDAO.queryBookById(id);
    }

    @Override
    public List<Book> queryAllBooks() throws SQLException {
        return bookDAO.queryAllBooks();
    }

    /**
     * 获取指定页面的Page对象
     *
     * @param pn        指定页码（1-based）
     * @param ecp       每页条目数
     * @param urlAction servlet url
     * @return
     */
    @Override
    public Page<Book> getPage(int pn, int ecp, String urlAction) throws SQLException {
        Page<Book> page = new Page<>();
        int ect = bookDAO.getEntryCountTotal();
        page.setEct(ect);
        int pt = ect / ecp;
        if (ect % ecp != 0) {
            pt += 1;
        }
        page.setPt(pt);
        page.setPn(pn);
        page.setUrlAction(urlAction);
        int eStart = (page.getPn() - 1) * page.getEcp();
        List<Book> books = bookDAO.queryBooksPerPage(eStart, ecp);
        page.setPes(books);
        return page;
    }

    @Override
    public Page<Book> getPageByPrice(int pn, double minPrice, double maxPrice, int ecp, String urlAction) throws SQLException {
        Page<Book> page = new Page<>();
        int ect = bookDAO.getEntryCountTotalByPrice(minPrice, maxPrice);
        page.setEct(ect);
        int pt = ect / ecp;
        if (ect % ecp != 0) {
            pt += 1;
        }
        page.setPt(pt);
        page.setPn(pn);
        page.setUrlAction(urlAction);
        int eStart = (page.getPn() - 1) * page.getEcp();
        List<Book> books = bookDAO.queryBooksPerPageByPrice(minPrice, maxPrice, eStart, ecp);
        page.setPes(books);
        return page;
    }
}
